﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LibMinecraft.Server;
using LibMinecraft.Model.Packets;
using LibMinecraft.Model;

namespace PartyCraftServer.Commands
{
    public class CmdCommand : Command
    {
        public override bool RequiresOp
        {
            get { return false; }
        }

        public override string DefaultCommand
        {
            get { return "cmd"; }
        }

        public override string Documentation
        {
            get { return "Returns a list of available commands.\nUsage: /cmd (page)"; }
        }

        public override void ExecuteCommand(RemoteClient client, params string[] parameters)
        {
            if (parameters.Length > 1)
            {
                client.PacketQueue.Enqueue(new ChatMessagePacket(ChatColor.Red + "Invalid parameters.  Use /cmd (page)."));
                return;
            }

            int pageNum = 1;
            if (parameters.Length == 1)
            {
                if (!int.TryParse(parameters[0], out pageNum))
                {
                    client.PacketQueue.Enqueue(new ChatMessagePacket(ChatColor.Red + "Invalid parameters.  Use /cmd (page)."));
                    return;
                }
            }
            pageNum--;
            int pages = AppDomain.CurrentDomain.GetAssemblies().ToArray()
                .SelectMany(s => s.GetTypes())
                .Where(p => typeof(Command).IsAssignableFrom(p) && p != typeof(Command) &&
                    ((Command)Activator.CreateInstance(p)).RequiresOp == (bool)client.Tags["op"]).Count();
            pages = (int)Math.Ceiling((double)pages / 5d);

            client.SendChat(ChatColor.Blue + "Command list (" + (pageNum + 1) + "/" + pages + "):");

            foreach (var t in AppDomain.CurrentDomain.GetAssemblies().ToArray()
                .SelectMany(s => s.GetTypes())
                .Where(p => typeof(Command).IsAssignableFrom(p) && p != typeof(Command) &&
                    ((Command)Activator.CreateInstance(p)).RequiresOp == (bool)client.Tags["op"])
                .OrderBy(p => ((Command)Activator.CreateInstance(p)).DefaultCommand)
                .Skip(pageNum * 5).Take(5))
            {
                Command c = (Command)Activator.CreateInstance(t);
                client.SendChat(ChatColor.Blue + "/" + c.DefaultCommand);
            }
        }
    }
}
